package org.zjx.command.composite;

import lombok.Getter;
import org.zjx.command.Command;
import org.zjx.command.basic.ScreenshotCommand;
import org.zjx.core.IWindow;
import org.zjx.util.ImageUtil;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.List;

@Getter
public class FindImageCommand extends Command {
    private BufferedImage screenshot;
    private final BufferedImage targetImage;
    private final Rectangle rectangle;
    private Point point;

    public FindImageCommand(IWindow targetWindow, BufferedImage screenshot, BufferedImage targetImage, Rectangle rectangle) {
        super(targetWindow, false, null);
        this.screenshot = screenshot;
        this.targetImage = targetImage;
        this.rectangle = rectangle;
    }

    @Override
    protected void doExecute() throws Exception {
        if (screenshot == null) {
            ScreenshotCommand screenshotCommand = new ScreenshotCommand(targetWindow);
            screenshotCommand.execute();
            screenshot = screenshotCommand.getScreenshot();
        }
        List<Point> points;
        if (rectangle != null) {
            BufferedImage image = ImageUtil.cutImage(screenshot, rectangle);
            points = ImageUtil.matchTemplate(image, targetImage);
        } else {
            points = ImageUtil.matchTemplate(screenshot, targetImage);
        }
        if (!points.isEmpty()) {
            if (rectangle != null) {
                this.point = new Point(points.get(0).x + rectangle.x + targetImage.getWidth() / 2, points.get(0).y + rectangle.y + targetImage.getHeight() / 2);
            } else {
                this.point = new Point(points.get(0).x + targetImage.getWidth() / 2, points.get(0).y + targetImage.getHeight() / 2);
            }
        }
    }

    public boolean findImage(){
        return point != null;
    }
}
